import { updateSysUserAvatarApi } from '@/api/custcare/sysuser/sysuser'
import { SetSysUser } from '@/api/custcare/sysuser/SysUserModel'
import {
    SendMessage,
    SysUserLoginParam
} from '@/api/custcare/talk/BackUserModel'
import {
    getSysUserInfoApi,
    sysUserLoginApi
} from '@/api/custcare/talk/back_user'
import { getUnreadMsgCountApi } from '@/api/custcare/visitor/visitor'
import { getInfoApi } from '@/api/system/user/user'
import useInstance from '@/hooks/useInstance'
import { StatusCode } from '@/http/request'
import { custCareUserStore } from '@/store/custcare'
import { menuStore } from '@/store/menu'
import { MESSAGE_CMD } from '@/types/CustcareEnum'
import { getToken } from '@/utils/auth'
import {
    getCustcareUserInfo,
    setCustcareExpireTime,
    setCustcareToken,
    setCustcareUserInfo
} from '@/utils/custcareAuth'
import { onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'

export default function useBase() {
    const custStore = custCareUserStore()
    const mStore = menuStore()
    const route = useRoute()

    const { global } = useInstance()

    const getOnMessage = (e: any) => {
        const msg = JSON.parse(e.detail.data)
        // console.log('收到消息: ', msg)
        if (msg.cmd == MESSAGE_CMD.CMD_HEART) {
            console.log('心跳: ', msg.content)
            return
        }
        custStore.setRealTimeMsg(msg)
        // console.log('route.path=', route.path)
        if (route.path !== '/custcare/talk') {
            global.$message({ message: '您有新的消息！', type: 'success' })
            mStore.setMenuAddNewText()
        }
    }

    const getOnClose = (e: any) => {
        // 监听关闭
        console.log('关闭了', e)
    }

    const getOnHeartBeat = () => {
        const custcareInfo = getCustcareUserInfo()
        if (custcareInfo) {
            const msg = reactive<SendMessage>({
                cmd: MESSAGE_CMD.CMD_HEART,
                channel_id: '',
                to_user_uuid: custcareInfo.uuid,
                type: 1,
                content: 'ping'
            })
            custStore.getSocket.sendMessage(msg)
        }
    }

    const goSocket = () => {
        window.addEventListener('onMessageWS', getOnMessage)
        window.addEventListener('onCloseWS', getOnClose)
        window.addEventListener('onHeartBeatWs', getOnHeartBeat)
        custStore.setSocket()
    }

    const getUnreadMsgCount = async () => {
        let res = await getUnreadMsgCountApi()
        if (res && res.code == StatusCode.Success) {
            console.log('未读消息数量=', res.data.count)
            if (res.data.count > 0) {
                mStore.setMenuAddNewText()
            }
        }
    }

    const userInfo = async () => {
        const userRes = await getSysUserInfoApi()
        console.log('客服信息=', userRes)
        if (userRes && userRes.code == StatusCode.Success) {
            setCustcareUserInfo(JSON.stringify(userRes.data))
            // 获得未读消息数量
            getUnreadMsgCount()
            // ws连接
            setTimeout(() => {
                goSocket()
            }, 1000)
        } else {
            global.$message({
                message: '获得客服信息失败！',
                type: 'error'
            })
        }
    }

    const login = async () => {
        const token = getToken() || ''
        if (token !== '') {
            // 更新客服头像
            const res = await getInfoApi()
            if (res && res.code == StatusCode.Success) {
                let param = reactive<SetSysUser>({
                    id: parseInt(res.data.id),
                    is_service: false
                })
                await updateSysUserAvatarApi(param)

                const loginModel = reactive<SysUserLoginParam>({
                    token: token
                })
                const userRes = await sysUserLoginApi(loginModel)
                console.log('登录结果：', userRes)
                if (userRes.code == StatusCode.Success) {
                    setCustcareToken(userRes.data.access_token)
                    setCustcareExpireTime(userRes.data.access_expire)
                    userInfo()
                }
            }
        }
    }

    onMounted(() => {
        login()
    })

    return {
        login
    }
}
